import { BaseModel } from './BaseModel';
import { query } from '../../config/database';

export interface IUser {
  id: string;
  username: string;
  email: string;
  password_hash: string;
  full_name?: string;
  role: 'admin' | 'user' | 'readonly';
  is_active: boolean;
  created_at: Date;
  updated_at: Date;
  last_login?: Date;
}

export class User extends BaseModel {
  constructor() {
    super('users');
  }
  
  // 根据用户名查找用户
  async findByUsername(username: string): Promise<IUser | null> {
    const result = await query(
      'SELECT * FROM users WHERE username = $1',
      [username]
    );
    return result.rows[0] || null;
  }
  
  // 根据邮箱查找用户
  async findByEmail(email: string): Promise<IUser | null> {
    const result = await query(
      'SELECT * FROM users WHERE email = $1',
      [email]
    );
    return result.rows[0] || null;
  }
  
  // 验证用户密码
  async validatePassword(username: string, password: string): Promise<IUser | null> {
    const result = await query(
      `SELECT * FROM users 
       WHERE username = $1 
       AND password_hash = crypt($2, password_hash)
       AND is_active = true`,
      [username, password]
    );
    return result.rows[0] || null;
  }
  
  // 创建用户（自动加密密码）
  async createUser(userData: {
    username: string;
    email: string;
    password: string;
    full_name?: string;
    role?: 'admin' | 'user' | 'readonly';
  }): Promise<IUser> {
    const result = await query(
      `INSERT INTO users (username, email, password_hash, full_name, role)
       VALUES ($1, $2, crypt($3, gen_salt('bf')), $4, $5)
       RETURNING *`,
      [
        userData.username,
        userData.email,
        userData.password,
        userData.full_name,
        userData.role || 'user'
      ]
    );
    return result.rows[0];
  }
  
  // 更新用户密码
  async updatePassword(id: string, newPassword: string): Promise<boolean> {
    const result = await query(
      `UPDATE users 
       SET password_hash = crypt($2, gen_salt('bf')), updated_at = CURRENT_TIMESTAMP
       WHERE id = $1`,
      [id, newPassword]
    );
    return result.rowCount > 0;
  }
  
  // 更新最后登录时间
  async updateLastLogin(id: string): Promise<boolean> {
    const result = await query(
      `UPDATE users 
       SET last_login = CURRENT_TIMESTAMP, updated_at = CURRENT_TIMESTAMP
       WHERE id = $1`,
      [id]
    );
    return result.rowCount > 0;
  }
  
  // 获取活跃用户列表
  async getActiveUsers(): Promise<IUser[]> {
    const result = await query(
      `SELECT id, username, email, full_name, role, created_at, updated_at, last_login
       FROM users 
       WHERE is_active = true
       ORDER BY created_at DESC`
    );
    return result.rows;
  }
  
  // 检查用户名是否已存在
  async isUsernameExists(username: string, excludeId?: string): Promise<boolean> {
    let sql = 'SELECT 1 FROM users WHERE username = $1';
    const params: any[] = [username];
    
    if (excludeId) {
      sql += ' AND id != $2';
      params.push(excludeId);
    }
    
    const result = await query(sql, params);
    return result.rows.length > 0;
  }
  
  // 检查邮箱是否已存在
  async isEmailExists(email: string, excludeId?: string): Promise<boolean> {
    let sql = 'SELECT 1 FROM users WHERE email = $1';
    const params: any[] = [email];
    
    if (excludeId) {
      sql += ' AND id != $2';
      params.push(excludeId);
    }
    
    const result = await query(sql, params);
    return result.rows.length > 0;
  }
}